from flask import request
from flask_restx import abort, reqparse

from app.common.excel_manager import excel_manager
from app.common.users_manager import users_manager
from app.models import userModel
from utils.utils import base_detail

from .base_view import AdminValidators


class UsersListCreateAPI(AdminValidators):
    """
    用户列表/新增用户
    since: 22.2.24
    """

    def get(self):
        params = request.args
        page = params.get("page", 1)
        page_size = params.get("pageSize", 10)
        kwd = params.get("keyword")
        role_id = params.get("roleId")
        is_superuser = params.get("isSuperuser")

        try:
            page = int(page)
            page_size = int(page_size)
        except:  # noqa
            page = 1
            page_size = 10

        if page_size > 50:
            abort(400, message="参数错误")

        filters = []
        if role_id:
            filters.append(userModel.User.role_id == role_id)
        if is_superuser:
            filters.append(userModel.User.is_superuser == is_superuser)
        if kwd:
            filters.append(userModel.User.username.contains(kwd))

        pagination = (
            userModel.User.query.filter(*filters)
            .order_by(userModel.User.id.desc())
            .paginate(page, page_size, error_out=False)
        )

        data = {
            "current_page": page,
            "data": [
                {
                    "username": user.username,
                    "create_time": user.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "realname": user.account_name,
                    "email": user.email,
                    "id": user.id,
                    "is_superuser": user.is_superuser,
                }
                for user in pagination.items
            ],
        }
        data = base_detail(data, pagination)
        return {"code": 200, "data": data}

    def post(self):
        parser = reqparse.RequestParser(bundle_errors=False)
        parser.add_argument("username", help="用户名不能为空", required=True)
        parser.add_argument("realname", help="姓名不能为空", required=True)
        parser.add_argument("email", help="邮箱不能为空", required=True)
        parser.add_argument("role_id", help="用户身份id未提供", required=True)
        parser.add_argument("is_superuser", help="是否管理员", type=bool)
        parser.add_argument("password", help="请输入密码", required=True)
        parser.add_argument("confirm_password", help="输入确认密码", required=True)
        params = parser.parse_args()

        params["account_name"] = params.pop("realname")
        users_manager.add_user(
            params.pop("username"),
            params.pop("email"),
            params.pop("role_id"),
            params.pop("password"),
            params.pop("confirm_password"),
            **params
        )

        return {"code": 200, "msg": "创建成功!"}


class UsersRetrieveUpdateDestroyAPI(AdminValidators):
    """
    用户详情/修改/删除
    """

    def get(self, user_id):
        user = users_manager.get_obj_or_error(id=user_id)
        data = users_manager.get_attr_to_dict(
            user,
            attrs=[
                "id",
                "create_time",
                "account_name",
                "email",
                "role_id",
                "project_id",
                "class_id",
                "is_superuser",
            ],
        )
        data["create_time"] = data["create_time"].strftime("%Y-%m-%d %H:%M:%S")
        data["realname"] = data.pop("account_name")

        return {"data": data}

    def put(self, user_id):
        parser = reqparse.RequestParser()
        parser.add_argument("username")
        parser.add_argument("realname")
        parser.add_argument("email")
        params = parser.parse_args()

        params["account_name"] = params.pop("realname")

        users_manager.update_user(user_id, **params)

        return {"code": 200, "data": "修改成功"}

    def delete(self, user_id):
        users_manager.delete_user(user_id)
        return {"code": 200, "data": "删除成功"}


class UsersBulkOperationsAPI(AdminValidators):
    """
    用户批量导入/模板
    """

    student_heads = ["*用户名", "*姓名", "*邮箱", "*密码"]

    @staticmethod
    def get_import_template(heads):
        return excel_manager.import_template_download("用户批量导入模板", "导入模板", heads=heads)

    def get(self):
        # role = request.args.get('role', default=0, type=int)
        heads = self.student_heads
        response = self.get_import_template(heads)
        return response

    @staticmethod
    def excel_handle(file, heads):
        df = excel_manager.verify_excel(file, verify_heads=heads, notnull_heads=heads)
        # 批量导入
        _, message = users_manager.bulk_import(df)
        return message

    def post(self):
        # role = request.form.get('role', default=0, type=int)
        heads = self.student_heads
        file = request.files.get("file")
        message = self.excel_handle(file, heads)
        return {"code": 200, "message": message}
